package com.hong.pdf2img;

import com.hong.pdf2img.utils.AppLogger;
import com.hong.pdf2img.utils.PdfToImageUtil;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import lombok.Setter;

import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

import static com.hong.pdf2img.MainApplication.*;

public class MainController {
    @FXML
    public Button text_btn_all;
    @FXML
    private Button choose_out_btn;
    @FXML
    private Button choose_pdf_btn;
    @FXML
    private Button genner_btn;  //生成图片
    @FXML
    private Button merge_btn;   //合并文档按钮
    @FXML
    private Button split_btn;   //拆分文档按钮
    @FXML
    private Button text_btn;    //获取文本按钮
    @FXML
    private ToggleGroup genner_type;    //生成图片的方式:1-对页面截图,2-获取文档中的图片
    @FXML
    private ToggleGroup img_format;     //图片格式
    @FXML
    private ToggleGroup img_type;           //图片形式:1-每个页面分开;2-生成一张长图
    @FXML
    private TextField img_quality_input;    //图片质量输入框
    @FXML
    private Slider img_quality_slider;  //图片质量滑动条
    @FXML
    private TextField page_size_input;
    @FXML
    private Label out_path_label;
    @FXML
    private ToggleGroup page_size;
    @FXML
    private TextArea show_result_box;
    @Setter
    private Stage primaryStage; // 存储主舞台的引用

    private List<File> pdfFileList = new ArrayList<>(); //存储已选的pdf文件

    public void setOutPathInput(String out_path_input) {
        out_path_label.setText(out_path_input);
    }

    /**
     * 设置图片质量输入框失去焦点监听器
     */
    public void setImgQualityInputFocusListener(){
        img_quality_input.focusedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                if (!newValue) { // 当失去焦点时
                    // 处理失去焦点事件
                    syncImgQualityValue();
                }
            }
        });
    }

    /**
     * 设置图片格式
     * @param event
     */
    @FXML
    void selectImgFormat(MouseEvent event) {
        String format= img_format.getSelectedToggle().getUserData().toString();
        MainApplication.img_format_value=format;
    }

    /**
     * 设置图片类型
     * @param event
     */
    @FXML
    void setImgType(MouseEvent event) {
        int type= Integer.parseInt(img_type.getSelectedToggle().getUserData().toString());
        MainApplication.img_type=type;
    }

    /**
     * 设置生成类型
     * @param event
     */
    @FXML
    void setGenerateType(MouseEvent event) {
        int type= Integer.parseInt(genner_type.getSelectedToggle().getUserData().toString());
        getImgType=type;
    }
    /**
     * 设置图片质量的文本框动作
     * @param keyEvent
     */
    @FXML
    public void setImgQualityValue(KeyEvent keyEvent) {
        if(keyEvent.getCode()== KeyCode.ENTER){
            syncImgQualityValue();
        }
    }

    /**
     * 同步输入框和滑动条的值
     */
    private void syncImgQualityValue(){
        String text=img_quality_input.getText();
            text=text.replaceAll("[^0-9]","");
            try{
                int value=Integer.parseInt(text);
                if(value>500) value=500;
                if(value<50) value=50;
                img_quality_slider.setValue(value);
                img_quality_input.setText(""+value);
                MainApplication.img_quality=value;
            }catch (Exception e){
                if(text.length()>2) img_quality_input.setText(text.substring(0,text.length()-2));
            }
    }
    /**
     * 设置图片质量滑动条动作
     * @param event
     */
    @FXML
    void setImgQualityValueBySlider(MouseEvent event) {
        int value=(int)img_quality_slider.getValue();
        img_quality_input.setText(""+value);
        MainApplication.img_quality=value;
    }
    /**
     * 选择输出目录
     * @param event
     */
    @FXML
    void ChooseOutPathAction(MouseEvent event) {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        // 设置文件选择对话框的标题
        directoryChooser.setTitle("选择保存的文件夹");
        // 显示文件选择对话框并获取选中的文件
        if(outputPath==null || outputPath.equals("") || !new File(outputPath).exists())
            directoryChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        else directoryChooser.setInitialDirectory(new File(outputPath));
        File selectedFile = directoryChooser.showDialog(primaryStage);
        if (selectedFile != null) {
            outputPath=selectedFile.getAbsolutePath();
            out_path_label.setText(selectedFile.getAbsolutePath());
            AppLogger.info("选择输出目录"+selectedFile.getAbsolutePath());
        }
    }

    /**
     * 选择pdf文件
     * @param event
     */
    @FXML
    void ChoosePdfFileAction(MouseEvent event) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PDF文件", "*.pdf"));
        fileChooser.setTitle("打开PDF文件");  // 设置文件选择对话框的标题
        String path=MainApplication.inputPath;
        if(path!=null && !path.equals("") && new File(MainApplication.inputPath).exists()) fileChooser.setInitialDirectory(new File(path)); //设置文件选择框的初始目录
        else fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        pdfFileList=fileChooser.showOpenMultipleDialog(primaryStage);
        if (pdfFileList==null || pdfFileList.isEmpty()) {
            showErrorDialog( "请选择文件");
            return;
        }
        show_result_box.setText("");
        String filePath=pdfFileList.get(0).getAbsolutePath();
        MainApplication.inputPath=filePath.substring(0,filePath.lastIndexOf(File.separator));
        for(File selectedFile:pdfFileList){
            if(selectedFile.isDirectory()){
                showErrorDialog("请选择文件");
                return;
            }
            if(selectedFile.isFile() && !selectedFile.getName().endsWith(".pdf")){
                showErrorDialog("请选择PDF文件");
                return;
            }
            show_result_box.appendText(selectedFile.getAbsolutePath()+"\n");
            AppLogger.info("选择文件:"+selectedFile.getAbsolutePath());
        }
    }

    /**
     * 生成图片按键动作
     * @param event
     */
    @FXML
    void GennerateImgAction(MouseEvent event) {
        String outPath= outputPath;
        if(outPath.equals("")){
            showErrorDialog("请选择输出目录");
            return;
        }
        if(pdfFileList==null || pdfFileList.isEmpty()){
            showErrorDialog("请选择PDF文件");
            return;
        }
        String pageSize="";     //处理页码范围
        RadioButton selectedRadioButton = (RadioButton) page_size.getSelectedToggle();
        if (selectedRadioButton != null) {
            pageSize = selectedRadioButton.getText();
        } else {
            showErrorDialog("请选择页码范围");
            return;
        }
        List<Integer> pageRange=getPageRange();
        for(File file:pdfFileList){
            try{
                String fileName=file.getAbsolutePath();
                if(file.equals("")) continue;
                if(!fileName.endsWith(".pdf")){
                    showErrorDialog("请选择PDF文件");
                    continue;
                }
                List<BufferedImage> imgDataList=null;
                String imgPrefix="page_";
                if(MainApplication.getImgType==1){  //对每个页面截图
                    if(pageSize.equals("全部页码")) imgDataList= PdfToImageUtil.pdfToImageForAllPage(fileName);
                    else imgDataList=PdfToImageUtil.pdfToImageForMultiPage(fileName,pageRange);
                }else { //获取文档中的原始图片
                    if(pageSize.equals("全部页码")) imgDataList= PdfToImageUtil.extractEmbeddedImages(fileName,null);
                    else imgDataList=PdfToImageUtil.extractEmbeddedImages(fileName,pageRange);
                    imgPrefix="img_";
                }
                String tempName=fileName.substring(fileName.lastIndexOf(File.separator)+1,fileName.lastIndexOf("."));
                if(MainApplication.img_type==1){    //图片类型 1-分页 2-单个长图
                    for(int i=0;i<imgDataList.size();i++){
                        int pageNum=i+1;
                        if(!pageSize.equals("全部页码")) pageNum=pageRange.get(i);  //实际页码的数字
                        String fileFulPathAndName=outPath+File.separator+tempName+File.separator+imgPrefix+pageNum+"."+MainApplication.img_format_value;
                        PdfToImageUtil.saveImage(imgDataList.get(i),outPath+File.separator+tempName,imgPrefix+pageNum+"."+MainApplication.img_format_value);
                        show_result_box.appendText(fileFulPathAndName+"\n");
                        AppLogger.info(fileFulPathAndName);
                    }
                }else{  //单个长图
                    BufferedImage image=PdfToImageUtil.mergeLongImage(imgDataList);
                    PdfToImageUtil.saveImage(image,outPath+File.separator+tempName,"long_image."+MainApplication.img_format_value);
                    String fileFulPathAndName=outPath+File.separator+tempName+File.separator+"long_image."+MainApplication.img_format_value;
                    show_result_box.appendText(fileFulPathAndName+"\n");
                    AppLogger.info(fileFulPathAndName);
                }
                show_result_box.appendText("转换完成\n");
                showInfoDialog("转换完成");
                AppLogger.info("转换完成");
            }catch (Exception e){
                AppLogger.error("发生异常",e);
            }
        }
    }
    /**
     * 获取文本按键动作
     * @param event
     */
    @FXML
    void GetTextsAction(MouseEvent event) {
        try {
            if(pdfFileList==null || pdfFileList.isEmpty()){
                showErrorDialog("请选择文件");
                return;
            }
            String text=PdfToImageUtil.getStrings(pdfFileList.get(0).getAbsolutePath(),getPageRange());
            FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("textDialog.fxml"));
            Scene scene = new Scene(fxmlLoader.load());
            Stage stage=new Stage();
            stage.setTitle("文本提取");
            stage.setScene(scene);
            TextDialogController textDialogController=fxmlLoader.getController();
            textDialogController.setText(text);
            textDialogController.setStage(stage);
            textDialogController.setShowResultBox(show_result_box);
            stage.show();
        }catch (Exception e){
            AppLogger.error("发生异常",e);
        }
    }
    /**
     * 获取所有文件文本并保存
     * @param event
     */
    @FXML
    void getAllFileTextAndSave(MouseEvent event) {
        try{
            if(pdfFileList==null || pdfFileList.isEmpty()){
                showErrorDialog("请选择文件");
                return;
            }
            for(File file:pdfFileList){
                String text=PdfToImageUtil.getStrings(file.getAbsolutePath(),null);
                File txtFile=new File(outputPath+File.separator+file.getName()+".txt");
                Files.writeString(txtFile.toPath(), text);
                show_result_box.appendText(txtFile.getAbsolutePath());
            }
            showInfoDialog("文件保存完成");
        }catch (Exception e){
            AppLogger.error("发生异常",e);
        }
    }
    /**
     * 合并文件按键动作
     * @param event
     */
    @FXML
    void MergeDocumentAction(MouseEvent event) {
        System.out.println("MergeDocumentAction click");
    }
    /**
     * 分割文件按键动作
     * @param event
     */
    @FXML
    void SplitDocumentAction(MouseEvent event) {
        System.out.println("SplitDocumentAction click");
    }

    /**
     * 处理手动输入的页码范围
     * @return
     */
    public List<Integer> getPageRange() {
        String pageSize="";     //处理页码范围
        RadioButton selectedRadioButton = (RadioButton) page_size.getSelectedToggle();
        if (selectedRadioButton != null) {
            pageSize = selectedRadioButton.getText();
        } else {
            showErrorDialog("请选择页码范围");
            return null;
        }
        if(pageSize.equals("手动输入")){
            if(pdfFileList.size()>1){
                showErrorDialog( "多个文件不支持手动输入页码，请选择单个文件或全部页码");
                return null;
            }
            pageSize=page_size_input.getText();
            if(pageSize.equals("")){
                showErrorDialog("请输入页码范围");
                return null;
            }
            String pageRangeStr=page_size_input.getText();
            List<Integer> pageRange = new ArrayList<>();
            String[] parts = pageRangeStr.split("[,，]");
            for(String s:parts){
                if(!s.contains("-")){
                    pageRange.add(Integer.parseInt(s));
                }else{
                    String[] range=s.split("-");
                    for(int i=Integer.parseInt(range[0]);i<=Integer.parseInt(range[1]);i++){
                        pageRange.add(i);
                    }
                }
            }
            return pageRange;
        }
        return null;
    }
}
